package com.gulimall.gulimallproduct.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gulimall.gulimallproduct.dao.CategoryBrandRelationDao;
import com.gulimall.gulimallproduct.service.CategoryBrandRelationService;
import com.gulimall.gulimallproduct.vo.Catalog3Vo;
import com.gulimall.gulimallproduct.vo.Catelog2Vo;
import io.netty.util.internal.StringUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.gulimallproduct.dao.CategoryDao;
import com.gulimall.gulimallproduct.entity.CategoryEntity;
import com.gulimall.gulimallproduct.service.CategoryService;
import org.thymeleaf.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所以分类
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((categoryEntities1, categoryEntities2) -> {
                    return (categoryEntities1.getSort()==null?0:categoryEntities1.getSort()) - (categoryEntities2.getSort()==null?0:categoryEntities2.getSort());
                }).collect(Collectors.toList());

        return categoryEntities;
    }

    @Override
    public void removeMenuByids(List<Long> list) {
        //TODO 检查当前删除的菜单，是否被其他地方引用
        baseMapper.deleteBatchIds(list);
    }

    /**
     * @param catelogId
     * @return
     * 查询某个属性的分类路径
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list=new ArrayList<>();
        List<Long> list1=findParentPath(catelogId,list);
        Collections.reverse(list1);
        return (Long[]) list1.toArray(new Long[list1.size()]);
    }

    /**
     * 级联跟新其他表中的分类字段
     * @param category
     */

    @Caching(evict = {
            @CacheEvict(value = "category",key = "'categoryLevel1'"),
            @CacheEvict(value = "category",key = "'getCatelogJson'")
    })
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 查出所有一级分类
     * @return
     */
    //缓存的分区（按业务类型分）
    @Cacheable(value = "category",key = "'categoryLevel1'")// 代表当前方法的结果需要缓存，如果缓存中有，方法不调用，如果缓存中没有，会调用方法
    @Override
    public List<CategoryEntity> getLeve1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    /**
     * 对三级分类的优化
     * 将数据库的多次查询变为一次
     * 本地锁
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {
             //拿到锁要先判断一下，是否已经吧数据放到缓存中
           String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
           if(!StringUtils.isEmpty(catalogJSON)){
               return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
               });
           }
            //数据库的多次查询变为一次
            List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
            //查出所有的一级分类
            List<CategoryEntity> leve1Categorys = getParentCid(categoryEntityList,0L);
            //封装数据
            Map<String, List<Catelog2Vo>> parentCid = leve1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //查到这个一级分类的二级分类
                List<CategoryEntity> categoryEntities = getParentCid(categoryEntityList,v.getCatId());
                List<Catelog2Vo> catelog2Vos = null;
                if (categoryEntities != null) {
                    catelog2Vos = categoryEntities.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(l2.getCatId().toString(), l2.getName(), v.getCatId().toString(), null);
                        //找当前二级分类下的三级分类
                        List<CategoryEntity> thirdCategory = getParentCid(categoryEntityList,l2.getCatId());
                        if(thirdCategory!=null){
                            //封装成指定格式
                            List<Catalog3Vo> collect = thirdCategory.stream().map(l3 -> {
                                Catalog3Vo catalog3Vo = new Catalog3Vo(l3.getCatId().toString(),l3.getName(),l2.getCatId().toString());
                                return catalog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(collect);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }
                return catelog2Vos;
            }));
        System.out.println("查询数据库成功");
            return parentCid;
    }
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        //数据库的多次查询变为一次
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        //查出所有的一级分类
        List<CategoryEntity> leve1Categorys = getParentCid(categoryEntityList,0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = leve1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(categoryEntityList,v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(l2.getCatId().toString(), l2.getName(), v.getCatId().toString(), null);
                    //找当前二级分类下的三级分类
                    List<CategoryEntity> thirdCategory = getParentCid(categoryEntityList,l2.getCatId());
                    if(thirdCategory!=null){
                        //封装成指定格式
                        List<Catalog3Vo> collect = thirdCategory.stream().map(l3 -> {
                            Catalog3Vo catalog3Vo = new Catalog3Vo(l3.getCatId().toString(),l3.getName(),l2.getCatId().toString());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        System.out.println("查询数据库成功");
        return parentCid;
    }

    /**
     * 使用redis对三级缓存进行优化
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatelogJson2() {
        //加入缓存逻辑，对象用json的形式存储，json可以跨平台
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if(StringUtils.isEmpty(catalogJSON)){
            //缓存中没有，查询数据库，放入缓存
            Map<String, List<Catelog2Vo>> catelogJsonFromDb;
            //之所以可以锁this是因为springboot中所有的组件在容器中都是单例的
            System.out.println("缓存每命中，查询数据库");
            //本地锁的方式
          /*  synchronized (this){
                 catelogJsonFromDb = getCatelogJsonFromDb();
                 String jsonString = JSON.toJSONString(catelogJsonFromDb);
                redisTemplate.opsForValue().set("catalogJSON",jsonString);
                return catelogJsonFromDb;
            }*/
            //redis 锁的方式
            try {
                return getCatelogJsonLockWithRedis();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //如果缓存中存在，直接转换后返回
        Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        System.out.println("缓存命中");
        return stringListMap;
    }

    /**
     * 使用redis的set nx 命令来实现分布式锁
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatelogJsonLockWithRedis() throws InterruptedException {
        String uuid = UUID.randomUUID().toString();
        Map<String, List<Catelog2Vo>> catelogJsonFromDb = null;
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if(lock){
            try{
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            if(!StringUtils.isEmpty(catalogJSON)){
                return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });

            }
            //重点：无论锁有没有获取成功，都要进行删除
                catelogJsonFromDb = getCatelogJsonFromDb();
                String jsonString = JSON.toJSONString(catelogJsonFromDb);
                redisTemplate.opsForValue().set("catalogJSON",jsonString);
                System.out.println("获取分布式锁成功并进行查询操作");
            }
            finally {
                String script="if redis.call(\"get\",KEYS[1]) == ARGV[1] \n" +
                        "then\n" +
                        "\treturn redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end;";
                Long Long = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return catelogJsonFromDb;
        }

        else{
            System.out.println("获取分布式锁失败，尝试重试");
            Thread.sleep(500);
            return  getCatelogJsonLockWithRedis();

        }
    }

    /**
     * redisson分布式锁
     * @return
     * @throws InterruptedException
     */
    public Map<String, List<Catelog2Vo>> getCatelogJsonLockWithRedisson() throws InterruptedException {
        RLock lock1 = redissonClient.getLock("CatelogJson-lock");
        lock1.lock();
        Map<String, List<Catelog2Vo>> catelogJsonFromDb = null;
            try{
                String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
                if(!StringUtils.isEmpty(catalogJSON)){
                    return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                    });

                }
                //重点：无论锁有没有获取成功，都要进行删除
                catelogJsonFromDb = getCatelogJsonFromDb();
                String jsonString = JSON.toJSONString(catelogJsonFromDb);
                redisTemplate.opsForValue().set("catalogJSON",jsonString);
                System.out.println("获取分布式锁成功并进行查询操作");
            }
            finally {
                lock1.unlock();
            }
            return catelogJsonFromDb;

    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> categoryEntities,Long parent_cid) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
        return collect;
    }

    /**
     * 递归找父id收集到list集合中
     * @param catelogId
     * @param list
     * @return
     */
    private List<Long> findParentPath(Long catelogId, List<Long> list) {
        list.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if(categoryEntity.getParentCid()!=0){
            findParentPath(categoryEntity.getParentCid(),list);
        }
        return list;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntit -> categoryEntit.getParentCid() == categoryEntity.getCatId())
                .map(meau -> {
                    meau.setChildren(getChildrens(meau, categoryEntities));
                    return meau;
                }).sorted((cate1, cate2) -> {
                    return (cate1.getSort()==null?0:cate1.getSort()) - (cate2.getSort()==null?0:cate2.getSort());
                }).collect(Collectors.toList());

        return collect;
    }

}